﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Mtbl;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.App;
using System.Transactions;

namespace WebApplication
{
    public partial class M_ProductCategory : BasePage
    {
        private static tblCustomer entCust = null;
        tblCust_ProdCat ent_Cust_ProdCat = new tblCust_ProdCat();
        tblCust_ProdCatBLL bll_Cust_ProdCat = new tblCust_ProdCatBLL();
        static List<tblCust_ProdCat> listCustProdCat = new List<tblCust_ProdCat>();

        app_tblCust_ProdCat entAppProdCat = new app_tblCust_ProdCat();
        app_tblCust_ProdCatBLL app_ProdCatBLL = new app_tblCust_ProdCatBLL();
        static List<app_tblCust_ProdCat> listAppProdCat = new List<app_tblCust_ProdCat>();
        static int cuid;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                cuid = GetEnt();
                //string uid = Request.QueryString[Constant.UrlParamName.CustomerUID];
                //cuid = Convert.ToInt32(uid);
                if (cuid <= 0)
                {
                    SetNoOption();
                    usermeg.Visible = false;
                    lblMeg.Text = ResourceManage.GetResourceString("msg200002");                    
                }
                else
                {
                    #region 填充listCustProdCat,listAppProdCat
                    ent_Cust_ProdCat.CustomerUID=cuid;
                    listCustProdCat = bll_Cust_ProdCat.GetListByENT(ent_Cust_ProdCat);
                    entAppProdCat.CustomerUID = cuid;
                    listAppProdCat = app_ProdCatBLL.GetListByENT(entAppProdCat);
                    #endregion
                    usermeg.Visible = true;
                    entCust = new tblCustomer();
                    tblCustomerBLL bll = tblCustomerBLL.GetInstance();
                    entCust.CustomerUID = cuid;                    
                    entCust = bll.GetEntity(entCust);
                }
                CreateProductCategory();
            }
        }

        #region
        /// <summary>
        /// 按照Product Category 生成全部的checklist
        /// </summary>
        private void CreateProductCategory()
        {
            List<string> tmp = new List<string>();
            tmp.Add("A"); tmp.Add("B"); tmp.Add("C"); tmp.Add("D"); tmp.Add("E");
            rp_Cate_All.DataSource = tmp;
            rp_Cate_All.DataBind();
        }

        /// <summary>
        /// 生成product category 部分的checklist
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rp_Cate_All_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string param = e.Item.DataItem as string;
            CheckBoxList cbl_categoy = e.Item.FindControl("cbl_cate") as CheckBoxList;
            Repeater rp_categoy = e.Item.FindControl("rp_cate") as Repeater;

            mtblProductCatBLL bllProductCate = mtblProductCatBLL.GetInstance();

            if (!string.IsNullOrEmpty(param) && cbl_categoy != null)
            {
                mtblProductCat ent_PC = new mtblProductCat();
                ent_PC.ProductCatID = param;
                List<mtblProductCat> listProductCat = bllProductCate.GetListByENT(ent_PC);
                cbl_categoy.DataSource = listProductCat;

                foreach (mtblProductCat ent in listProductCat)
                {
                    if (ent != null)
                        ent.LastModifyBy = ent.ProductCat_Eng + " " + ent.ProductCat_Chi;
                }

                cbl_categoy.DataTextField = "LastModifyBy";
                cbl_categoy.DataValueField = "ProductCatUID";
                cbl_categoy.DataBind();

                rp_categoy.DataSource = listProductCat;
                rp_categoy.DataBind();
            }
        }

        /// <summary>
        /// 生成 和绑定被选项  product sub category 部分的checklist
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rp_cate_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            mtblProductCat tmp = e.Item.DataItem as mtblProductCat;
            mtblProductSubCat ent_PSC = new mtblProductSubCat();
            ent_PSC.ProductCatUID = tmp.ProductCatUID;

            List<mtblProductSubCat> listProductSubCat = mtblProductSubCatBLL.GetInstance().GetListByENT(ent_PSC);
            CheckBoxList cbl_subcategoy = e.Item.FindControl("cbl_subcate") as CheckBoxList;

            foreach (mtblProductSubCat ent in listProductSubCat)
            {
                if (ent != null)
                    ent.LastModifyBy = ent.ProductSubCat_Eng + " " + ent.ProductSubCat_Chi;
            }

            if (tmp != null && cbl_subcategoy != null)
            {
                cbl_subcategoy.DataSource = listProductSubCat;
                cbl_subcategoy.DataTextField = "LastModifyBy";
                cbl_subcategoy.DataValueField = "ProductSubCatUID";
                cbl_subcategoy.DataBind();
            }

            ///根据数据绑定选中的项
            if (entCust != null)
            {
                #region
                entAppProdCat=new app_tblCust_ProdCat();
                entAppProdCat.CustomerUID = entCust.CustomerUID; 
                entAppProdCat.Deleted = -1;
                entAppProdCat.ProductCatUID = tmp.ProductCatUID;
                var list_App_ProdCat = app_ProdCatBLL.GetListByENT(entAppProdCat);

                ent_Cust_ProdCat = new tblCust_ProdCat();
                ent_Cust_ProdCat.CustomerUID = entCust.CustomerUID;
                ent_Cust_ProdCat.Deleted = Constant.IsDelete.no;
                ent_Cust_ProdCat.ProductCatUID = tmp.ProductCatUID;
                var list_Cust_ProdCat = tblCust_ProdCatBLL.GetInstance().GetListByENT(ent_Cust_ProdCat);
                #endregion
                #region
                List<int> tempList = new List<int>();
                for (int i = 0; i < list_Cust_ProdCat.Count(); i++) {
                    int Count = list_App_ProdCat.Where(a=>a.ProductSubCatUID==list_Cust_ProdCat[i].ProductSubCatUID).Count();
                    if (Count == 0)
                    {
                        tempList.Add(list_Cust_ProdCat[i].ProductSubCatUID);
                    }
                }
                foreach(app_tblCust_ProdCat item in list_App_ProdCat){
                    if (item.Deleted == 0)
                    {
                        int temp = item.ProductSubCatUID;
                        tempList.Add(temp);
                    }
                }
                #endregion

                if (tempList.Count > 0)
                {
                    foreach (int item in tempList)
                    {
                        for (int i = 0; i < cbl_subcategoy.Items.Count; i++)
                        {
                            if (cbl_subcategoy.Items[i].Value == item.ToString()){
                                cbl_subcategoy.Items[i].Selected = true;
                                HiddenField_val.Value += cbl_subcategoy.Items[i].Value+",";
                            }
                        }
                    }
                }
            }
        }
        #endregion

        protected void LbtnSave_Click(object sender, EventArgs e)
        {
            if (GetEnt() > 0)
            {
                entCust = new tblCustomer();
                entCust = tblCustomerBLL.GetInstance().GetEntity(GetEnt());
                entAppProdCat = new app_tblCust_ProdCat();
                #region 保存方案
                //1:如果app_tblCust_ProdCat没有包含当前Customer的修改数据,当用户修改后获取当前勾选的数据新增到App_MainMarket表中
                //2:如果app_tblCust_ProdCat已经有Customer的数据存在,则在分3个步骤 
                //2-> 1)对比当前勾选是否已经存在,若存在,并且Deleted=0,从源表中获取数据添加到Save方法  2)如果没有,表示新数据,作为新纪录添加到Save方法 3)表中存在,但是当前没有勾选,记录到unselectd中;
                #endregion
                #region
                List<app_tblCust_ProdCat> tempApplist = new List<app_tblCust_ProdCat>();
                entAppProdCat.CustomerUID = entCust.CustomerUID;
                var tempAppList = app_ProdCatBLL.GetListByENT(entAppProdCat);
                #endregion

                if (entCust != null)
                {

                    List<IntTemp> unselectd_uid = new List<IntTemp>();
                    for (int i = 0; i < rp_Cate_All.Items.Count; i++)
                    {
                        Repeater re_cat = rp_Cate_All.Items[i].FindControl("rp_cate") as Repeater;
                        CheckBoxList cbl_cate = rp_Cate_All.Items[i].FindControl("cbl_cate") as CheckBoxList;
                        for (int j = 0; j < re_cat.Items.Count; j++)
                        {

                            CheckBoxList cbl_subcategoy = re_cat.Items[j].FindControl("cbl_subcate") as CheckBoxList;
                            for (int k = 0; k < cbl_subcategoy.Items.Count; k++)
                            {
                                if (cbl_subcategoy.Items[k].Selected)
                                {
                                    entAppProdCat = new app_tblCust_ProdCat();
                                    int item = Convert.ToInt32(cbl_subcategoy.Items[k].Value);
                                    var resuleTbl = listCustProdCat.Where(a => a.CustomerUID == cuid && a.ProductSubCatUID == item).ToList();
                                    var resuleApp = listAppProdCat.Where(a => a.CustomerUID == cuid && a.ProductSubCatUID == item).ToList();
                                    #region
                                    if (resuleApp.Count() > 0)
                                    {
                                        foreach (app_tblCust_ProdCat C in resuleApp)
                                        {
                                            entAppProdCat.Cust_ProdCatUID = C.Cust_ProdCatUID;
                                            entAppProdCat.CustomerUID = cuid;
                                            //entAppProdCat.ProductCatUID = C.ProductCatUID;
                                            entAppProdCat.ProductCatUID = Convert.ToInt32(cbl_cate.Items[i].Value);
                                            entAppProdCat.ProductSubCatUID = C.ProductSubCatUID;
                                            entAppProdCat.Deleted = Constant.IsDelete.no;
                                        }
                                    }
                                    else if (resuleApp.Count() == 0 && resuleTbl.Count() > 0)
                                    {
                                        foreach (tblCust_ProdCat C in resuleTbl)
                                        {
                                            entAppProdCat.Cust_ProdCatUID = C.Cust_ProdCatUID;
                                            entAppProdCat.CustomerUID = cuid;
                                            //entAppProdCat.ProductCatUID = C.ProductCatUID;
                                            entAppProdCat.ProductCatUID = Convert.ToInt32(cbl_cate.Items[i].Value);
                                            entAppProdCat.ProductSubCatUID = C.ProductSubCatUID;
                                            entAppProdCat.Deleted = Constant.IsDelete.no;
                                        }
                                    }
                                    else
                                    {
                                        #region 获取ProductCatUID的值
                                        mtblProductSubCatBLL bll = new mtblProductSubCatBLL();
                                        mtblProductSubCat ent = new mtblProductSubCat();
                                        ent.ProductSubCatUID = item;
                                        int CatUID = bll.GetListByENT(ent).Select(a => a.ProductCatUID).FirstOrDefault();
                                        #endregion
                                        entAppProdCat.Cust_ProdCatUID = 0;
                                        entAppProdCat.CustomerUID = cuid;
                                        entAppProdCat.ProductSubCatUID = item;
                                        //entAppProdCat.ProductCatUID = Convert.ToInt32(CatUID);
                                        entAppProdCat.ProductCatUID = Convert.ToInt32(cbl_cate.Items[i].Value);
                                        entAppProdCat.Deleted = Constant.IsDelete.no;
                                    }
                                    tempApplist.Add(entAppProdCat);
                                    #endregion
                                }
                                else
                                {
                                    int item = Convert.ToInt32(cbl_subcategoy.Items[k].Value);
                                    int tmptbl = listCustProdCat.Where(a => a.ProductSubCatUID == item).Count();
                                    int tmpApp = tempAppList.Where(a => a.ProductSubCatUID == item).Count();
                                    if (tmptbl > 0 | tmpApp > 0)
                                    {
                                        IntTemp tmp = new IntTemp();
                                        tmp.ProductCatUID = Convert.ToInt32(cbl_cate.Items[i].Value);
                                        tmp.ProductSubCateUID = item;
                                        unselectd_uid.Add(tmp);
                                    }
                                }
                            }

                        }
                    }
                    TransactionOptions sptions = new TransactionOptions();
                    sptions.Timeout = new TimeSpan(0, 5, 0);
                    sptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, sptions))
                    {
                        _save(tempApplist, cuid);
                        _delete(unselectd_uid, cuid);
                        WriteToLog();
                        try
                        {
                            scope.Complete();
                            lblMeg.Text = ResourceManage.GetResourceString("msg200004");
                        }
                        catch (Exception ex)
                        {
                            lblMeg.Text = ResourceManage.GetResourceString("msg200003");
                        }
                    }
                }
                else
                {
                    SetNoOption();
                    lblMeg.Text = ResourceManage.GetResourceString("msg200014");
                }
            }
            else {
                LbtnSave.Enabled = false;
                lblMeg.Text = ResourceManage.GetResourceString("msg400004");
            }
        }

        private void _save(List<app_tblCust_ProdCat> listProdSubCat, int custUID)
        {
            #region
            List<app_tblCust_ProdCat> tmpApplist = new List<app_tblCust_ProdCat>();
            entAppProdCat = new app_tblCust_ProdCat();
            entAppProdCat.CustomerUID = custUID;
            entAppProdCat.Deleted = -1;
            tmpApplist = app_ProdCatBLL.GetListByENT(entAppProdCat);
            List<tblCust_ProdCat> tmpTbllist = new List<tblCust_ProdCat>();
            ent_Cust_ProdCat.CustomerUID = custUID;
            ent_Cust_ProdCat.Deleted = Constant.IsDelete.no;
            tmpTbllist = bll_Cust_ProdCat.GetListByENT(ent_Cust_ProdCat);
            #endregion

            for (int i = 0; i < listProdSubCat.Count(); i++) {
                int App_tal = tmpApplist.Where(a => a.ProductSubCatUID == listProdSubCat[i].ProductSubCatUID).Count();
                int tbl_tal = tmpTbllist.Where(a => a.ProductSubCatUID == listProdSubCat[i].ProductSubCatUID).Count();

                if (App_tal <= 0 && tbl_tal <= 0)
                {
                    listProdSubCat[i].Deleted = Constant.IsDelete.no;
                    AddItem(listProdSubCat[i] as app_tblCust_ProdCat,custUID);
                }
                else if (App_tal >= 1)
                {
                    var val = tmpApplist.Where(a => a.ProductSubCatUID == listProdSubCat[i].ProductSubCatUID).ToList();
                    int tamp = val.Where(a => a.Deleted == Constant.IsDelete.yes).Count();
                    if(tamp==1)
                    {
                        DeleteItem(listProdSubCat[i] as app_tblCust_ProdCat, custUID); 
                    }
                }
            }
        }

        private void _delete(List<IntTemp> listProdSubCat, int custUID)
        {
            #region
            entAppProdCat = new app_tblCust_ProdCat();
            entAppProdCat.CustomerUID = custUID;
            entAppProdCat.Deleted = -1;
            List<app_tblCust_ProdCat> ApptempList = app_ProdCatBLL.GetListByENT(entAppProdCat);
            List<tblCust_ProdCat> tmpTbllist = new List<tblCust_ProdCat>();
            ent_Cust_ProdCat = new tblCust_ProdCat();
            ent_Cust_ProdCat.CustomerUID = custUID;
            ent_Cust_ProdCat.Deleted = 0;
            tmpTbllist = bll_Cust_ProdCat.GetListByENT(ent_Cust_ProdCat);
            #endregion

            for (int i = 0; i < listProdSubCat.Count(); i++)
            {
                #region
                entAppProdCat = new app_tblCust_ProdCat();
                entAppProdCat.CustomerUID = custUID;
                entAppProdCat.ProductSubCatUID = listProdSubCat[i].ProductSubCateUID;
                #endregion

                int App_tal = ApptempList.Where(a => a.ProductSubCatUID == listProdSubCat[i].ProductSubCateUID).Count();
                int Tbl_tal = tmpTbllist.Where(a => a.ProductSubCatUID == listProdSubCat[i].ProductSubCateUID).Count();

                if (App_tal == 1 && Tbl_tal == 0)
                {
                    DeleteItem(entAppProdCat, custUID);
                }
                else if(App_tal==0&&Tbl_tal==1){
                    var items = tmpTbllist.Where(a => a.ProductSubCatUID == listProdSubCat[i].ProductSubCateUID).ToList();
                    foreach(tblCust_ProdCat item in items)
                    {
                        entAppProdCat.Cust_ProdCatUID = item.Cust_ProdCatUID;
                        entAppProdCat.ProductCatUID = item.ProductCatUID;
                        entAppProdCat.Deleted = Constant.IsDelete.yes;
                        AddItem(entAppProdCat,custUID);
                    }
                }
            }

        }        

        /// <summary>
        /// 将TblCust_BusNature更新到App_TblCust_BusNature
        /// </summary>
        /// <param name="ent"></param>
        void UpDateTbltoApp(tblCust_ProdCat ent)
        {
            entAppProdCat = new app_tblCust_ProdCat();
            entAppProdCat.CustomerUID = cuid;
            entAppProdCat.ProductCatUID = ent.ProductCatUID;
            entAppProdCat.Remark = ent.Remark;
            entAppProdCat.Deleted = ent.Deleted;
            entAppProdCat.ProductSubCatUID = ent.ProductSubCatUID;
            entAppProdCat.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            app_ProdCatBLL.InsertENT(entAppProdCat);
        }

        /// <summary>
        /// member修改了记录,临时记录将会添加到App_表中
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        void AddItem(app_tblCust_ProdCat item, int Cuid)
        {
            entAppProdCat = new app_tblCust_ProdCat();
            entAppProdCat.Cust_ProdCatUID = item.Cust_ProdCatUID;
            entAppProdCat.ProductCatUID = item.ProductCatUID;
            entAppProdCat.ProductSubCatUID = item.ProductSubCatUID;
            entAppProdCat.CustomerUID = item.CustomerUID;
            entAppProdCat.Deleted = item.Deleted;
            entAppProdCat.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            app_ProdCatBLL.InsertENT(entAppProdCat);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        void UpdateItem(app_tblCust_ProdCat item, int Cuid)
        {
            entAppProdCat = new app_tblCust_ProdCat();
            entAppProdCat.CustomerUID = Cuid;
            entAppProdCat.ProductSubCatUID = item.ProductSubCatUID;
            entAppProdCat.Deleted = item.Deleted;
            entAppProdCat.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            app_ProdCatBLL.UpdateENT(entAppProdCat);
        }

        /// <summary>
        /// 删除临时表的记录
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        void DeleteItem(app_tblCust_ProdCat item, int Cuid)
        {
            entAppProdCat.CustomerUID = Cuid;
            entAppProdCat.ProductSubCatUID = item.ProductSubCatUID;
            entAppProdCat.AppCust_ProdCatUID = item.AppCust_ProdCatUID;
            app_ProdCatBLL.DeleteENT(entAppProdCat);
        }
        
        private void SetNoOption()
        {
            LbtnSave.Enabled = false; 
            lblMeg.Text = ResourceManage.GetResourceString("msg200001");
        }

        protected void LbtnQuit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/M_ProductCategory.aspx");
        }

        protected void WriteToLog()
        {
            string LoginName = tblCust_WebLoginBLL.GetInstance().GetENT(GetMemberLoginUID()).LoginName.ToString();
            string addlog = string.Empty;
            string dellog = string.Empty;
            mtblProductSubCat entProSubCat = new mtblProductSubCat();
            List<mtblProductSubCat> list = mtblProductSubCatBLL.GetInstance().GetListByENT(entProSubCat);
            string[] add = HiddenFiled_add.Value.Split(',');
            string[] delete = HiddenFiled_del.Value.Split(',');
            if (add.Length > 1 | delete.Length > 1)
            {
                for (int i = 0; i < add.Length - 1; i++)
                {
                    var result = list.Where(a => a.ProductSubCatUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                    foreach (mtblProductSubCat item in result)
                    {
                        addlog += item.ProductSubCat_Eng + ",";
                    }
                }
                for (int i = 0; i < delete.Length - 1; i++)
                {
                    var result = list.Where(a => a.ProductSubCatUID == Convert.ToInt32(delete[i])).Select(p => p).ToList();
                    foreach (mtblProductSubCat item in result)
                    {
                        dellog += item.ProductSubCat_Eng + ",";
                    }
                }
                if (addlog.Length > 1)
                    addlog = " Add " + addlog.Substring(0, addlog.Length - 1);
                else
                    addlog = "";
                if (dellog.Length > 1)
                    dellog = " Delete " + dellog.Substring(0, dellog.Length - 1);
                else
                    dellog = "";

                tblHistory entlog = new tblHistory();
                Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
                entlog.HistoryCatUID = 2;
                entlog.HistoryTypeUID = 29;
                entlog.CustomerUID = GetEnt();
                entlog.Cust_MemberUID = 0;
                entlog.ContactPersonUID = 0;
                entlog.History_Detail = LoginName + " {"+CompanyName.Text+"}{ProductCategory}" + addlog + dellog;
                entlog.LastModifyBy = LoginName;
                int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
            }
        }
    }
}